﻿/********************************************************************************

** 作者： XmPlatform

** 描述：XmHttpServer

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Web;
using System.Diagnostics;
using System.Reflection;
using System.Data;
using System.Text;
using System.Xml;
using System.Collections;
using System.Configuration;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using XmHttpServer;
using XmHttpServer.Rest;

namespace XmHttpServer
{
    /// <summary>
    /// 工具类
    /// </summary>
    public class Tools
    {
        public static string currentServerUrl = "";
        public static LogWriter infoLog = new LogWriter(@"logs", "log", 3, 0, false);

        /// <summary>
        /// 将dataTable转换为xml字符串
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static string DataTableToXml(DataTable dt)
        {
            if (dt.Rows.Count == 0) return Tools.NullXml();
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sb.Append("<tableData>");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                sb.Append("<record>");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    sb.Append("<" + dt.Columns[j].ColumnName + ">" + XmlReplace(dt.Rows[i][j].ToString()) + "</" + dt.Columns[j].ColumnName + ">");
                }
                sb.Append("</record>");
            }
            sb.Append("</tableData>");
            return sb.ToString();
        }
        /// <summary>
        /// xml替换特殊字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string XmlReplace(string str)
        {
            if (!string.IsNullOrEmpty(str))
            {
                str = str.Replace("&", "&amp;");
                str = str.Replace("<", "&lt;");
                str = str.Replace(">", "&gt;");
                str = str.Replace("'", "&apos;");
                str = str.Replace("\"", "&quot;");
                return str;
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 将dataTable转换为xmlDocument
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public static XmlDocument DataTableToXmlDoc(DataTable dt)
        {
            if (dt.Rows.Count == 0) return Tools.NullXmlDoc();
            XmlDocument xmlDoc = new XmlDocument();
            //XmlNode xmlNode;
            XmlElement xmlChildElement;
            XmlElement xmlElement;
            XmlElement xmlRootElement;

            //加入XML的声明段落
            //方式一
            //xmlNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            //xmlDoc.AppendChild(xmlNode);
            //方式二
            XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(dec);
            //加入一个根元素
            xmlRootElement = xmlDoc.CreateElement("", "tableData", "");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                xmlElement = xmlDoc.CreateElement("", "record", "");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    xmlChildElement = xmlDoc.CreateElement(dt.Columns[j].ColumnName);
                    xmlChildElement.InnerText = dt.Rows[i][j].ToString();
                    xmlElement.AppendChild(xmlChildElement);
                }
                xmlRootElement.AppendChild(xmlElement);
            }
            xmlDoc.AppendChild(xmlRootElement);
            return xmlDoc;
        }
        /// <summary>
        /// 返回空xml字符串
        /// </summary>
        /// <returns></returns>
        public static string NullXml()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sb.Append("<tableData>");
            sb.Append("</tableData>");
            return sb.ToString();
        }
        /// <summary>
        /// 返回空xmlDocument
        /// </summary>
        /// <returns></returns>
        public static XmlDocument NullXmlDoc()
        {
            XmlDocument xmlDoc = new XmlDocument();
            //XmlNode xmlNode;
            XmlElement xmlRootElement;
            //加入XML的声明段落
            //方式一
            //xmlNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            //xmlDoc.AppendChild(xmlNode);
            //方式二
            XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(dec);
            //加入一个根元素
            xmlRootElement = xmlDoc.CreateElement("", "tableData", "");
            xmlDoc.AppendChild(xmlRootElement);
            return xmlDoc;
        }
        public static string StringXml(string childName, string innerText)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sb.Append("<tableData>");
            sb.Append("<record>");
            sb.Append("<" + childName + ">" + Tools.XmlReplace(innerText) + "</" + childName + ">");
            sb.Append("</record>");
            sb.Append("</tableData>");
            return sb.ToString();
        }
        /// <summary>
        /// 返回空xmlDocument
        /// </summary>
        /// <returns></returns>
        public static XmlDocument StringXmlDoc(string childName, string innerText)
        {
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement xmlRootElement;
            XmlElement xmlChildElement;
            //加入XML的声明段落
            //方式一
            //xmlNode = xmlDoc.CreateNode(XmlNodeType.XmlDeclaration, "", "");
            //xmlDoc.AppendChild(xmlNode);
            //方式二
            XmlDeclaration dec = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
            xmlDoc.AppendChild(dec);
            //加入一个根元素
            xmlRootElement = xmlDoc.CreateElement("", "tableData", "");
            xmlChildElement = xmlDoc.CreateElement(string.IsNullOrEmpty(childName) ? "result" : childName);
            xmlChildElement.InnerText = innerText;
            xmlRootElement.AppendChild(xmlChildElement);
            xmlDoc.AppendChild(xmlRootElement);
            return xmlDoc;
        }
        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="ex"></param>
        public static void Log(Exception ex)
        {
            Tools.infoLog.WriterLog(ex);
        }
        /// <summary>
        /// 日志记录
        /// </summary>
        /// <param name="ex"></param>
        public static void Log(string info)
        {
            Tools.infoLog.WriterLog(info);
        }

        /// <summary>
        /// 将字符串转换为DateTime
        /// </summary>
        /// <param name="dateTimeString"></param>
        /// <returns></returns>
        public static DateTime tryParseTime(string dateTimeString)
        {
            if (string.IsNullOrEmpty(dateTimeString)) return DateTime.Now;
            try
            {
                return DateTime.Parse(dateTimeString);
            }
            catch
            {
                return DateTime.Now;
            }
        }

        public static string SerializeToXml(object o)
        {
            System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(o.GetType());
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            serializer.Serialize(ms, o);
            ms.Position = 0;
            System.Xml.XmlDocument dom = new System.Xml.XmlDocument();
            dom.LoadXml(System.Text.ASCIIEncoding.ASCII.GetString(ms.GetBuffer()));
            if (dom.DocumentElement == null) return string.Empty;
            return dom.DocumentElement.OuterXml;
        }

        //************************************转换queryString *************************//
        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString)
        {
            if (string.IsNullOrEmpty(queryString)) return new NameValueCollection();
            return GetQueryString(queryString, null, true);
        }

        /// <summary>
        /// 将查询字符串解析转换为名值集合.
        /// </summary>
        /// <param name="queryString"></param>
        /// <param name="encoding"></param>
        /// <param name="isEncoded"></param>
        /// <returns></returns>
        public static NameValueCollection GetQueryString(string queryString, Encoding encoding, bool isEncoded)
        {
            if (string.IsNullOrEmpty(queryString)) return new NameValueCollection();
            queryString = queryString.Replace("?", "");
            NameValueCollection result = new NameValueCollection(StringComparer.OrdinalIgnoreCase);
            if (!string.IsNullOrEmpty(queryString))
            {
                int count = queryString.Length;
                for (int i = 0; i < count; i++)
                {
                    int startIndex = i;
                    int index = -1;
                    while (i < count)
                    {
                        char item = queryString[i];
                        if (item == '=')
                        {
                            if (index < 0)
                            {
                                index = i;
                            }
                        }
                        else if (item == '&')
                        {
                            break;
                        }
                        i++;
                    }
                    string key = null;
                    string value = null;
                    if (index >= 0)
                    {
                        key = queryString.Substring(startIndex, index - startIndex);
                        value = queryString.Substring(index + 1, (i - index) - 1);
                    }
                    else
                    {
                        key = queryString.Substring(startIndex, i - startIndex);
                    }
                    if (isEncoded)
                    {
                        result[MyUrlDeCode(key, encoding)] = MyUrlDeCode(value, encoding);
                    }
                    else
                    {
                        result[key] = value;
                    }
                    if ((i == (count - 1)) && (queryString[i] == '&'))
                    {
                        result[key] = string.Empty;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 解码URL.
        /// </summary>
        /// <param name="encoding">null为自动选择编码</param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string MyUrlDeCode(string str, Encoding encoding)
        {
            if (encoding == null)
            {
                Encoding utf8 = Encoding.UTF8;
                //首先用utf-8进行解码                     
                string code = HttpUtility.UrlDecode(str.ToUpper(), utf8);
                //将已经解码的字符再次进行编码.
                string encode = HttpUtility.UrlEncode(code, utf8).ToUpper();
                if (str == encode)
                    encoding = Encoding.UTF8;
                else
                    encoding = Encoding.GetEncoding("gb2312");
            }
            return HttpUtility.UrlDecode(str, encoding);

        }
        //************************************转换queryString *************************//

        ///// <summary>
        ///// 获取服务端的ip地址
        ///// </summary>
        ///// <returns></returns>
        public static string getServerIp()
        {
            IPAddress[] arrIPAddresses = Dns.GetHostAddresses(Dns.GetHostName());
            if (arrIPAddresses != null && arrIPAddresses.Length > 0)
            {
                return arrIPAddresses[0].ToString();
            }
            else
            {
                return "127.0.0.1";
            }
        }

        public static StringBuilder ServeHelp(IDictionary<string, KeyValuePair<Type, Dictionary<string, System.Reflection.MethodInfo>>> typeReference,HttpServer server,string adr, int port)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("<body><head><title>XmPlatform-XmHttpServer</title></head><H1>XmHttpServer</H1><br><H2>Rest接口列表</H2>");

            //string adr = "locahost";//
            //adr = Tools.getServerIp();
            string href = "http://" + adr + ":" + port + "/";
            string allHref = ""; //完整url
            string ipHref = "";//ip后的url

            //sb.Append("<br>调用示例：" + href + "类名/方法名?参数名=值&参数名=值<br>");
            //sb.Append("<br>例如：<a href='" + href + "SqlService/forTest?input=输入字符串' target='_blank'>" + href + "SqlService/forTest?input=输入字符串</a><br><br><br>");
            foreach (KeyValuePair<string, KeyValuePair<Type, Dictionary<string, MethodInfo>>> pair in typeReference)
            {
                //sb.AppendFormat("<li>{0}", pair.Key);
                //sb.Append("<br>");
                foreach (KeyValuePair<string, MethodInfo> methodsDef in pair.Value.Value)
                {
                    if ("listAllTables".Equals(methodsDef.Value.Name)) continue;
                    if ("getAllRecordByTableName".Equals(methodsDef.Value.Name)) continue;
                    string contentType = methodsDef.Value.GetCustomAttributes(typeof(Xml), false).Length > 0 ? "xml" : (methodsDef.Value.GetCustomAttributes(typeof(Json), false).Length > 0?"json":"text");
                    sb.AppendFormat("<li><b>{0}</b>&nbsp;[{1}]&nbsp;&nbsp;{2}", methodsDef.Value.Name, contentType, getAttributeSummary(methodsDef.Value));

                    if (methodsDef.Value.GetParameters().Length > 0)
                    {
                        sb.Append("</li><br>");
                        string methodUrl = "";
                        foreach (ParameterInfo pi in methodsDef.Value.GetParameters())
                        {
                            if (pi.ParameterType.Name.Equals("HttpContext")) continue;
                            //sb.AppendFormat("<li>参数名称： <b>{0}</b>&nbsp;&nbsp;&nbsp;&nbsp;参数类型： <b>{1}</b> </li>", pi.Name, pi.ParameterType.Name);
                            methodUrl = methodUrl + pi.Name + "=" + pi.ParameterType.Name + "&";
                        }
                        if (!string.IsNullOrEmpty(methodUrl)) methodUrl = "?" + methodUrl.Substring(0, methodUrl.Length - 1);
                        ipHref = "" + pair.Key + "/" + methodsDef.Value.Name + methodUrl;
                        allHref = href + pair.Key + "/" + methodsDef.Value.Name + methodUrl;
                        methodUrl = pair.Key + "/" + methodsDef.Value.Name + methodUrl;
                        sb.Append("<a href='" + allHref + "' target='_blank'>" + allHref + "</a><br><br>");
                    }
                    else
                    {
                        allHref = href + pair.Key + "/" + methodsDef.Value.Name;
                        sb.Append("</li><br><a href='" + allHref + "' target='_blank'>" + allHref + "</a><br><br>");
                    }
                }
            }
            if(server.Directorys.Count>0)
            {
                sb.Append("<br><br><H2>文件服务列表</H2>");
                foreach(string urlPath in server.Directorys)
                {
                    string path = urlPath;
                    if (path.StartsWith("/")) path = path.Substring(1);
                    sb.Append("<li><b>" + path + "</b>&nbsp;[html]&nbsp;&nbsp;</li><br><a href='" + href + path + "' target='_blank'>" + href + path + "</a><br><br>");
                }
            }
            sb.Append("</body>");
            return sb;
        }

        //获取attribute注释
        private static string getAttributeSummary(MethodInfo mi)
        {
            try
            {
                RestMethod method = (RestMethod)mi.GetCustomAttributes(typeof(RestMethod), false)[0];
                if (method != null)
                {
                    return method.Comment;
                }
                else
                {
                    return "";
                }
            }
            catch
            {
                return "";
            }
        }
        public static int fileIndex = 1;
        /// <summary>
        /// 递归得到某个文件夹下的所有文件列表
        /// </summary>
        /// <param name="dir">文件夹路径</param>
        /// <returns></returns>
        public static string getFileList(string dir)
        {
            StringBuilder sb = new StringBuilder();
            string folder = "";
            try
            {
                DirectoryInfo direct = new DirectoryInfo(dir);
                foreach (DirectoryInfo d in direct.GetDirectories())     //查找子目录   
                {
                    sb.Append(getFileList(direct + "\\" + d.ToString() + "\\"));
                }
                foreach (FileInfo f in direct.GetFiles())             //查找文件 
                {
                    folder = dir.Substring(System.Windows.Forms.Application.StartupPath.Length).Replace("\\", "/");
                    if (!folder.EndsWith("/"))
                    {
                        folder = folder + "/";
                    }
                    sb.Append("<file" + fileIndex + ">" + folder + f.Name + "</file" + fileIndex + ">");
                    fileIndex++;
                }
                Tools.fileIndex = 1;
            }
            catch { }
            return sb.ToString();
        }
        //获取服务器端设置的更新文件列表
        public static string[] getUpdateFileList()
        {
            string updateFileName = Tools.configGetValue("UpdateFileNames");
            string[] updateFileNames = Regex.Split(updateFileName, "\n", RegexOptions.IgnoreCase);
            return updateFileNames;
        }
        /// <summary>
        /// 返回指定目录下的所有文件列表（html）
        /// </summary>
        /// <param name="path">文件夹路径</param>
        /// <param name="hrefPre">超链接前缀</param>
        /// <returns></returns>
        public static string GetFileListHtml(string path, string hrefPre)
        {
            string result = "<html><head><title>Fileslist</title></head><body>";
            result += "<font size=\"3\" face=\"verdana\">";
            result += "<h1>Navigate</h1>";

            result += "<h2>Dirs</h2>";
            foreach (string s in Directory.GetDirectories(path))
            {
                string[] splited = s.Split('\\');
                string name = splited[splited.Length - 1];
                string encodeName = System.Web.HttpUtility.UrlEncode(name);
                result += "<a href=\"" + hrefPre + encodeName + "/" + "\">" + name + "</a></br>";
            }
            result += "<h2>Files</h2>";

            foreach (string s in Directory.GetFiles(path))
            {
                string[] splited = s.Split('\\');
                string name = splited[splited.Length - 1];
                string encodeName = System.Web.HttpUtility.UrlEncode(name);
                result += "<a href=\"" + hrefPre + encodeName + "\">" + name + "</a></br>";
            }
            result += "</font></body></html>";
            return result;
        }
        /// <summary>
        /// 获取Config.xml中的用户
        /// </summary>
        /// <returns></returns>
        public static NameValueCollection configGetAllUserValue()
        {
            NameValueCollection nv = new NameValueCollection();
            XmlDocument xDoc = new XmlDocument();
            try
            {
                string exeName = System.Windows.Forms.Application.ExecutablePath;
                exeName = exeName.Substring(exeName.LastIndexOf("\\") + 1);
                xDoc.Load(System.Windows.Forms.Application.StartupPath + "\\Config.xml");

                XmlNode xNode;
                XmlNodeList xNodeList;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//appSettings//users");
                xNodeList = xNode.SelectNodes("//user");
                if (xNodeList != null)
                    foreach (XmlNode node in xNodeList)
                    {
                        xElem = (XmlElement)node;
                        if (xElem != null)
                        {
                            nv.Add(xElem.GetAttribute("key"), xElem.GetAttribute("value"));
                        }
                    }
                else
                    return nv;
            }
            catch (Exception ex)
            {
                string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                ex.Source = "错误源：" + className + " " + "调用方法：" + methodName;
                Tools.Log(ex);
                return nv;
            }
            return nv;
        }
        /// <summary>
        /// 往Config.xml中添加用户
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        public static void configSetUserValue(string userName, string password)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                string exeName = System.Windows.Forms.Application.ExecutablePath;
                exeName = exeName.Substring(exeName.LastIndexOf("\\") + 1);
                xDoc.Load(System.Windows.Forms.Application.StartupPath + "\\Config.xml");

                XmlNode xNode;
                XmlElement xElem1;
                XmlElement xElem2;
                xNode = xDoc.SelectSingleNode("//appSettings//users");
                xElem1 = (XmlElement)xNode.SelectSingleNode("//user[@key='" + userName + "']");
                if (xElem1 != null) xElem1.SetAttribute("value", password);
                else
                {
                    xElem2 = xDoc.CreateElement("user");
                    xElem2.SetAttribute("key", userName);
                    xElem2.SetAttribute("value", password);
                    xNode.AppendChild(xElem2);
                }
                xDoc.Save(System.Windows.Forms.Application.StartupPath + "\\Config.xml");
            }
            catch (Exception ex)
            {
                string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                ex.Source = "错误源：" + className + " " + "调用方法：" + methodName;
                Tools.Log(ex);
            }
        }
        /// <summary>
        /// 根据config的值
        /// </summary>
        /// <param name="appKey">add的key</param>
        /// <returns></returns>
        public static string configGetValue(string appKey)
        {
            XmlDocument xDoc = new XmlDocument();
            try
            {
                string exeName = System.Windows.Forms.Application.ExecutablePath;
                exeName = exeName.Substring(exeName.LastIndexOf("\\") + 1);
                xDoc.Load(System.Windows.Forms.Application.StartupPath + "\\Config.xml");

                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//appSettings");
                xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
                if (xElem != null)
                    return xElem.GetAttribute("value");
                else
                    return "";
            }
            catch (Exception ex)
            {
                string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                ex.Source = "错误源：" + className + " " + "调用方法：" + methodName;
                Tools.Log(ex);
                return "";
            }
        }
        /// <summary>
        /// 设置config的值
        /// </summary>
        /// <param name="appKey">add的key</param>
        /// <param name="appValue">值</param>
        public static void configSetValue(string appKey, string appValue)
        {
            try
            {
                XmlDocument xDoc = new XmlDocument();
                string exeName = System.Windows.Forms.Application.ExecutablePath;
                exeName = exeName.Substring(exeName.LastIndexOf("\\") + 1);
                xDoc.Load(System.Windows.Forms.Application.StartupPath + "\\Config.xml");

                XmlNode xNode;
                XmlElement xElem1;
                XmlElement xElem2;
                xNode = xDoc.SelectSingleNode("//appSettings");
                xElem1 = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
                if (xElem1 != null) xElem1.SetAttribute("value", appValue);
                else
                {
                    xElem2 = xDoc.CreateElement("add");
                    xElem2.SetAttribute("name", appKey);
                    xElem2.SetAttribute("value", appValue);
                    xNode.AppendChild(xElem2);
                }
                xDoc.Save(System.Windows.Forms.Application.StartupPath + "\\Config.xml");
            }
            catch (Exception ex)
            {
                string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                ex.Source = "错误源：" + className + " " + "调用方法：" + methodName;
                Tools.Log(ex);
            }
        }


        /// <summary>
        /// 获取config的所有设置的值
        /// </summary>
        /// <returns></returns>
        public static string configAllValue()
        {
            XmlDocument xDoc = new XmlDocument();
            //xml
            StringBuilder sb = new StringBuilder();
            sb.Append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>");
            sb.Append("<tableData>");
            try
            {
                string exeName = System.Windows.Forms.Application.ExecutablePath;
                exeName = exeName.Substring(exeName.LastIndexOf("\\") + 1);
                xDoc.Load(System.Windows.Forms.Application.StartupPath + "\\Config.xml");

                XmlNode xNode;
                XmlElement xElem;
                xNode = xDoc.SelectSingleNode("//appSettings");
                string appKey = "";
                string appValue = "";
                sb.Append("<record>");
                foreach (XmlNode childNode in xNode.ChildNodes)
                {
                    if (childNode.NodeType == XmlNodeType.Element)
                    {
                        xElem = (XmlElement)childNode;
                        if (xElem != null)
                        {
                            appKey = xElem.GetAttribute("key");
                            if (string.IsNullOrEmpty(appKey)) appKey = "";
                            appValue = xElem.GetAttribute("value");
                            if (string.IsNullOrEmpty(appValue)) appValue = "";
                            if (!"ConnectionString".Equals(appKey))
                            {
                                sb.Append("<" + appKey.ToUpper() + ">" + Tools.XmlReplace(appValue) + "</" + appKey.ToUpper() + ">");
                            }

                        }
                    }
                }
                sb.Append("</record>");
            }
            catch (Exception ex)
            {
                string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
                string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                ex.Source = "错误源：" + className + " " + "调用方法：" + methodName;
                Tools.Log(ex);
                return "";
            }
            sb.Append("</tableData>");
            return sb.ToString();
        }


        /// <summary>
        /// 设置开机启动
        /// </summary>
        /// <param name="bFlag">是否开机启动</param>
        /// <param name="strName">注册表主键名</param>
        /// <param name="strPath">程序路径</param>
        public static void RunWhenStart(bool bFlag, string strName, string strPath)
        {

            Microsoft.Win32.RegistryKey rootKey = Microsoft.Win32.Registry.LocalMachine;
            Microsoft.Win32.RegistryKey runKey = rootKey.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");

            if (bFlag == true)
            {
                try
                {
                    runKey.SetValue(strName, strPath);
                    rootKey.Close();
                }
                catch (Exception ex)
                {
                    string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
                    string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    ex.Source = "错误源：" + className + " " + "调用方法：" + methodName;
                    Tools.Log(ex);
                }

            }
            else
            {
                try
                {
                    runKey.DeleteValue(strName);
                    rootKey.Close();
                }
                catch (Exception ex)
                {
                    string className = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString();
                    string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
                    ex.Source = "错误源：" + className + " " + "调用方法：" + methodName;
                    Tools.Log(ex);
                }
            }
        }
        public static bool isPortInUse(string port)
        {
            bool use = false;
            Process p = new Process();
            p.StartInfo = new ProcessStartInfo("netstat", "-an");
            p.StartInfo.CreateNoWindow = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.RedirectStandardOutput = true;
            p.Start();
            string result = p.StandardOutput.ReadToEnd().ToLower();//最后都转换成小写字母
            string ip1 = "127.0.0.1";
            string ip2 = "0.0.0.0";
            System.Net.IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(Dns.GetHostName());
            System.Net.IPAddress[] addressList = ipEntry.AddressList;
            List<string> ipList = new List<string>();
            ipList.Add(ip1);
            ipList.Add(ip2);
            for (int i = 0; i < addressList.Length; i++)
            {
                ipList.Add(addressList[i].ToString());
            }
            for (int i = 0; i < ipList.Count; i++)
            {
                if (result.IndexOf("tcp    " + ipList[i] + ":" + port) >= 0)
                {
                    string[] resultArray = Regex.Split(result, "\r\n", RegexOptions.IgnoreCase);
                    for (int j = 0; j < resultArray.Length; j++)
                    {
                        if (resultArray[j].IndexOf("tcp    " + ipList[i] + ":" + port) >= 0 && resultArray[j].IndexOf("listening") > 0)
                        {
                            use = true;
                            break;
                        }
                    }
                }
            }
            return use;
        }

        public static bool isNumber(string input)
        {
            Regex reg = new Regex("^[0-9]+$");
            Match ma = reg.Match(input);
            if (ma.Success)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public static void OpenIEByUrl(String url)
        {
            System.Diagnostics.Process myProcess = new System.Diagnostics.Process();
            myProcess.StartInfo.FileName = "iexplore.exe";
            myProcess.StartInfo.Arguments = url;
            myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized; //IE窗口最大化
            myProcess.Start();
        }

















    }
}